package com.nulp.psycho.db.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.nulp.psycho.db.ConnectionManager;
import com.nulp.psycho.db.dao.BaseDao;
import com.nulp.psycho.db.mapping.Converter;
import com.nulp.psycho.db.model.QuestionAnswer;

public class QuestionAnswerDao implements BaseDao{

	private final String ADD_QUESTION_ANSWER = "INSERT INTO question_answer (question_id, answer_id) VALUES (?,?)";
	private final String GET_QUESTION_ANSWER_BY_ID = "SELECT * FROM question_answer WHERE id = ?";
	private final String REMOVE_QUESTION_ANSWER = "DELETE FROM question_answer WHERE id = ?";
	private final String UPDATE_QUESTION_ANSWER = "UPDATE question_answer SET question_id=?, answer_id=? WHERE id = ?";
	
	
	@Override
	public <T> void create(T element) {
		QuestionAnswer temp = (QuestionAnswer) element;
		Connection connection = ConnectionManager.getInstance().getConnection();
		try (PreparedStatement preparedStatement = connection
				.prepareStatement(ADD_QUESTION_ANSWER)) {
			preparedStatement.setInt(1, temp.getQuestionId());
			preparedStatement.setInt(2, temp.getAnswerId());
			preparedStatement.executeUpdate();
		} catch (SQLException e) {
		} finally {
			ConnectionManager.getInstance().release(connection);
		}		
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T read(Integer id) {
		Connection connection = ConnectionManager.getInstance().getConnection();
		QuestionAnswer qa = null;
		try (PreparedStatement statement = connection
				.prepareStatement(GET_QUESTION_ANSWER_BY_ID)) {
			statement.setInt(1, id);
			ResultSet rs = statement.executeQuery();
			if (rs.next())
				qa = Converter.<QuestionAnswer> fromResaultSetToObject(rs,
						QuestionAnswer.class);
		} catch (SQLException e) {
		} finally {
			ConnectionManager.getInstance().release(connection);
		}
		return (T) qa;	
	}

	@Override
	public void delete(Integer id) {
		Connection connection = ConnectionManager.getInstance().getConnection();
		try (PreparedStatement preparedStatement = connection
				.prepareStatement(REMOVE_QUESTION_ANSWER)) {
			preparedStatement.setInt(1, id);
			preparedStatement.executeUpdate();
		} catch (SQLException e) {
		} finally {
			ConnectionManager.getInstance().release(connection);
		}		
	}

	@Override
	public <T> void update(T element) {
		QuestionAnswer temp = (QuestionAnswer) element;
		Connection connection = ConnectionManager.getInstance().getConnection();
		try (PreparedStatement preparedStatement = connection
				.prepareStatement(UPDATE_QUESTION_ANSWER)) {
			preparedStatement.setInt(3, temp.getId());
			preparedStatement.setInt(1, temp.getQuestionId());
			preparedStatement.setInt(2, temp.getAnswerId());
			preparedStatement.executeUpdate();
		} catch (SQLException e) {
		} finally {
			ConnectionManager.getInstance().release(connection);
		}		
	}
	
}
